package com.mdd.system.resolvers;

import cn.dev33.satoken.SaManager;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mdd.common.aop.CurrentUser;
import com.mdd.system.entity.SystemAuthAdmin;
import com.mdd.system.entity.SystemAuthDept;
import com.mdd.system.mapper.SystemAuthAdminMapper;
import com.mdd.system.mapper.SystemAuthDeptMapper;
import com.mdd.system.vo.SystemAuthAdminInformVo;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;

public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

	@Resource
	SystemAuthAdminMapper systemAuthAdminMapper;
	@Resource
	SystemAuthDeptMapper systemAuthDeptMapper;

	@Override
	public boolean supportsParameter(MethodParameter methodParameter) {
		//判断方法参数是否带有@CurrentUser注解且参数类型为SystemAuthAdmin或其子类
		return methodParameter.hasParameterAnnotation(CurrentUser.class) && SystemAuthAdminInformVo.class.isAssignableFrom(methodParameter.getParameterType());
	}

	@Override
	public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) {
		Object adminId = SaManager.getStpLogic("admin").getLoginId();
		SystemAuthAdmin systemAuthAdmin = systemAuthAdminMapper.selectOne(
				new QueryWrapper<SystemAuthAdmin>()
						.select("id,username,nickname,avatar, role_ids,dept_ids,post_ids,is_disable")
						.eq("id", adminId)
						.eq("is_delete", 0)
						.last("limit 1"));
		SystemAuthDept systemAuthDept = systemAuthDeptMapper.selectById(systemAuthAdmin.getDeptIds());
		//获取当前登录用户
		systemAuthAdmin.setDeptCode(systemAuthDept.getDeptCode());
		SystemAuthAdminInformVo systemAuthAdminInformVo=new SystemAuthAdminInformVo();
		BeanUtil.copyProperties(systemAuthAdmin,systemAuthAdminInformVo);
		return systemAuthAdminInformVo;
	}

}
